/**
 * 
 */
package fr.aprr.odyssee.client.view;

import java.util.ArrayList;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.CanvasPixelArray;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.canvas.dom.client.ImageData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;

import fr.aprr.odyssee.client.model.Hover;
import fr.aprr.odyssee.client.model.Patrouille;
import fr.aprr.odyssee.client.model.Vh;



/**
 * @author PHAM
 *
 */
public class CanvasWidget extends Composite implements HasText {

	private static CanvasWidgetUiBinder uiBinder = GWT
			.create(CanvasWidgetUiBinder.class);
	
	interface CanvasWidgetUiBinder extends UiBinder<Widget, CanvasWidget> {
	}

	/**
	 * Because this class has a default constructor, it can
	 * be used as a binder template. In other words, it can be used in other
	 * *.ui.xml files as follows:
	 * <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	 *   xmlns:g="urn:import:**user's package**">
	 *  <g:**UserClassName**>Hello!</g:**UserClassName>
	 * </ui:UiBinder>
	 * Note that depending on the widget that is used, it may be necessary to
	 * implement HasHTML instead of HasText.
	 */
	
	static final String SUPPORTBROWSER = "Your browser does not support the HTML5 Canvas";
	static final String HOVER1 = "VH 1";
	static final String HOVER2 = "Patrouille 2";
	static final int REFRESH_RATE = 25;
	static final int HEIGHT_CANVAS = 120;
    static final int WIDTH_CANVAS = 850;
    final CssColor RED = CssColor.make("red");
    final CssColor GREEN = CssColor.make("green");
    final CssColor BLUE = CssColor.make("blue");
    
    
    
    ImageData vehiculeData;
    CanvasPixelArray vehiculeDataArray;
    
    Patrouille patrouille;
    Vh vh;
    
    int mouseX, mouseY;
    
	Context2d context;
	Context2d backcontext;
	Context2d hovercontext;
	
	Canvas backcanvas;
	
	ArrayList<Hover> listHover;
	
	@UiField(provided = true)
	  Canvas canvas;
	
	@UiField(provided = true)
	  Canvas canvasHover;
	
	@UiField
	Label label;

	
	public CanvasWidget() {
		System.out.println("Display Canvas");
		
		canvas = Canvas.createIfSupported();
		backcanvas = Canvas.createIfSupported();
		canvasHover = Canvas.createIfSupported();
		if (canvas == null) {
			label.setText(SUPPORTBROWSER);
			return;
		}
		
		// draw autoroute
		creatCanvas();
		
		// draw Vehicules
		creatVehiculeCanvas();
		
		// Initial Hover
		initialHover();
		
		// Initial Handler
		initHandlers();
		
		
		// update value
		updateATTab();
		
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	public void initialHover(){
		canvasHover.setWidth(WIDTH_CANVAS + "px");
		canvasHover.setHeight(HEIGHT_CANVAS + "px");
		canvasHover.setCoordinateSpaceWidth(WIDTH_CANVAS);
		canvasHover.setCoordinateSpaceHeight(HEIGHT_CANVAS);
		
		hovercontext = canvasHover.getContext2d();
		
		Hover hover1 = new Hover(75, 9, 10, 100, HOVER1 );
		Hover hover2 = new Hover(372, 10, 10, 100, HOVER2);
		listHover = new ArrayList<Hover>();
		listHover.add(hover1);
		listHover.add(hover2);
		
	  
	}
	public CanvasWidget(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));

		// Can access @UiField after calling createAndBindUi
	}

	public void creatVehiculeCanvas(){
		backcanvas.setWidth(WIDTH_CANVAS + "px");
        backcanvas.setHeight(HEIGHT_CANVAS + "px");
		backcanvas.setCoordinateSpaceWidth(WIDTH_CANVAS);
		backcanvas.setCoordinateSpaceHeight(HEIGHT_CANVAS);
		
		backcontext = backcanvas.getContext2d();
		    
		// creat object vehicules
		patrouille = new Patrouille();
		patrouille.getImageElement(backcontext);
		
      //  patrouille.draw(backcontext);
        
        vh = new Vh();
        vh.draw(backcontext);
        
     //   RootPanel.get().add(backcanvas);
        
       
        
        context.drawImage(backcontext.getCanvas(), 0, 0);
        
        System.out.println("Draw Vehicule");
	}
    public void creatCanvas(){
    	
    	canvas.setWidth(WIDTH_CANVAS + "px");
        canvas.setHeight(HEIGHT_CANVAS + "px");
        canvas.setCoordinateSpaceWidth(WIDTH_CANVAS);
        canvas.setCoordinateSpaceHeight(HEIGHT_CANVAS);
        
        context = canvas.getContext2d();
        
        
        
        // autoroute 1
        context.beginPath();
        
        context.setFillStyle(RED);
        context.fillRect(3, 20,300, 12);
        context.setFillStyle(RED);
        context.fillRect(3, 85, 300, 12);
        
        for (int i = 4; i <= 300; i=i+50) {
        	context.setStrokeStyle(RED);
        	context.moveTo(i, 32);
            context.lineTo(i, 85);
            context.stroke();
		}
        context.closePath();
        
        
     // autoroute 2
        context.beginPath();
        
        context.setFillStyle(GREEN);
        context.fillRect(300, 20,200, 12);
        context.setFillStyle(GREEN);
        context.fillRect(300, 85, 200, 12);
        
        for (int i = 300; i <= 490; i=i+50) {
        	context.setStrokeStyle(GREEN);
        	context.moveTo(i, 32);
            context.lineTo(i, 85);
            context.stroke();
		}
               
        context.closePath();
        
     // autoroute 3
        
        context.beginPath();
        
        context.setFillStyle(BLUE);
        context.fillRect(490, 20, 340, 12);
        context.setFillStyle(BLUE);
        context.fillRect(490, 85, 340, 12);
        
        for (int i = 490; i < 840; i=i+50) {
        	context.setStrokeStyle(BLUE);
        	context.moveTo(i, 32);
            context.lineTo(i, 85);
            context.stroke();
		}
       //draw end
        context.moveTo(829, 32);
        context.lineTo(829, 85);
        context.stroke();
        
        context.closePath();
        
        if (context.isPointInPath(mouseX, mouseY)){
        	
        }
    }
    
    // Initial Handlers
    public void initHandlers(){
    	
    	 // Generer Popup
        final PopupPanel popup = new PopupPanel();
        final Label label = new Label();
        popup.add( label );
    	
    	// move handler
    	canvasHover.addMouseMoveHandler(new MouseMoveHandler() {
			
			@Override
			public void onMouseMove(MouseMoveEvent event) {
				// TODO Auto-generated method stub
				
				mouseX = event.getRelativeX(canvasHover.getElement());
				mouseY = event.getRelativeY(canvasHover.getElement());
				
				boolean hit = false;
				
				for (Hover hover : listHover) {
					int alphaX = mouseX - hover.pointx;
					int alphaY = mouseY - hover.pointy;
					
					if (alphaX*alphaX + alphaY*alphaY < hover.hrXr) {
						//System.out.println("hover");
						label.setText( hover.tooltip);
	                    popup.setPopupPosition( event.getScreenX()+10, event.getClientY() + 70);
	                    popup.show();
	                    hit = true;
					}
					
					if (!hit) {
						popup.hide();
					}
				}
			}
		});
    	
    	
    		
    }
    
    // Update autoroute Tab
    public void updateATTab(){
    	final Timer timer = new Timer() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				doUpdate();
			}
		};
		
		timer.scheduleRepeating(REFRESH_RATE);
    }
    
    public void doUpdate(){
    	label.setText("Possition Tab autoroute : x = "+ mouseX + ", y = " + mouseY);
    }
    /**
	 * Gets invoked when the default constructor is called
	 * and a string is provided in the ui.xml file.
	 */
	public void setText(String text) {
		label.setText(text);
	}
	public String getText() {
     return label.getText();
	}

}
